// ctrl_auth_utils.go
package controllers

import (
	"bsm/services"
	"net/http"

	jwt "github.com/appleboy/gin-jwt/v2"
	"github.com/gin-gonic/gin"
)

type AuthController interface {
	RefreshToken(ctx *gin.Context)
	GetUserInfo(ctx *gin.Context)
	ValidateToken(ctx *gin.Context)
}

type authControllerImpl struct {
	authMiddleware *jwt.GinJWTMiddleware
	sessionService services.RedisSessionService
}

func NewAuthController(authMiddleware *jwt.GinJWTMiddleware, sessionService services.RedisSessionService) AuthController {
	return &authControllerImpl{
		authMiddleware: authMiddleware,
		sessionService: sessionService,
	}
}

func (c *authControllerImpl) RefreshToken(ctx *gin.Context) {
	// 由GIN-JWT中间件处理Token刷新
	c.authMiddleware.RefreshHandler(ctx)
}

func (c *authControllerImpl) GetUserInfo(ctx *gin.Context) {
	claims := jwt.ExtractClaims(ctx)
	ctx.JSON(http.StatusOK, gin.H{
		"code": 0,
		"data": claims,
	})
}

func (c *authControllerImpl) ValidateToken(ctx *gin.Context) {
	// Token验证由中间件完成，这里只需返回成功
	claims := jwt.ExtractClaims(ctx)
	ctx.JSON(http.StatusOK, gin.H{
		"code":  0,
		"valid": true,
		"user": gin.H{
			"user_id":   claims["user_id"],
			"user_name": claims["user_name"],
			"org_code":  claims["org_code"],
		},
	})
}
